package com.dys.filter;

import javax.servlet.*;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author: 疾风
 * @ClassName: EncodeFilter
 * @Description: 编码过滤器
 * @CreateDate: 2024/09/26
 * @Version: v1.0.0
 */
public class EncodeFilter implements Filter {
    private String encode;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // filterConfig 帮我们获取Filter初始化参数：
        String encodingFormat = filterConfig.getInitParameter("encode");
        // 假如web.xml中没有配置init-param 这里就会出500错误--空指针异常
        this.encode = Objects.requireNonNullElse(encodingFormat, "UTF-8");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1.设置请求信息的解码格式
        servletRequest.setCharacterEncoding(encode);
        // 2.设置响应信息的编码格式
        servletResponse.setCharacterEncoding(encode);
        // 3.设置浏览器的解码格式
        String decodingFormat = "text/html;charset=" + encode;
        servletResponse.setContentType(decodingFormat);
        // 4.放行资源: 放行到下一个过滤器or请求资源
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
